// ==UserScript==
// @name         QianDao Script
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  web qiandao script.
// @author       LaoTie
// @match        https://juejin.cn/*
// @icon
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

(async function () {
    'use strict';
    setInterval(() => {
        console.log('签到',formattedDate(),formattedTime());
        window.location.href='https://juejin.cn/user/center/signin';
    },3600000);
    if(load()===formattedDate()){
        console.log('今日已签到',formattedDate(),formattedTime());
        return; 
    }
    check_DAY();
})();

function check_DAY() {
    new Promise((resolve, reject) => {
        setTimeout(() => {
            findButton('.signin.btn');
            findButton('.signedin.btn');
            resolve();
        }, 1000);
    }).then(() => {
        setTimeout(() => {
            to_lottery();
        },1000);
    }).then(() => {
        setTimeout(() => {
            save(formattedDate());
        },1000);
    });
}

function to_lottery() {
    new Promise((resolve, reject) => {
        setTimeout(() => {
            findButton('.btn-area .btn');
            resolve();
        }, 1000);
    }).then(() => {
        setTimeout(() => {
            lottery();
        }, 1100);
    });
}

function lottery(){
    new Promise((resolve, reject) => {
        findButton('.btn.btn-free');
    }).then(() => {
        console.log('抽奖完成',btn,formattedDate(),formattedTime());
    });
}

function formattedDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
}

function formattedTime() {
    const date = new Date();
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
}

function findButton(cls) {
    const btn=document.querySelector(cls);
    if(btn!=null){
        btn.click();
    }
}

function load() {
    return GM_getValue('data', '');
}

function save(date) {
    GM_setValue('data', date);
}


